﻿//------------------------------------------------------------------------------
//  
//------------------------------------------------------------------------------
#region Imported Namespaces
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;

using SSRS;
using PHSRAG.Insight21.Reports;
using PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.SearchContext;
using AgreementsConstants = PHSRAG.Insight21.InsightUtilities.Constants.AgreementsConstants;

#endregion

namespace PHSRAG.Insight21.Agreements.Reports {

    
    public class sqlProjectionsReport : sqlReport
    {

        // Account Type Column Name, needed in download to excel
        private const string AccountTypeValueColName = "AccountTypeValue";
        private const string FundNumberKey = "FundNumberKey_deab9152-370e-4f9c-8577-c612f835e960";
        private const string ClosingDateKey = "ClosingDateKey_deab9152-370e-4f9c-8577-c612f835e960";
        
        public sqlProjectionsReport(string pageUrl)
            : base(pageUrl)
        {
            doHashtable = true;
            doCustomExcelReport = true;
        }
        
        public override string ReportName {
            get {
                return "Agmt_Projections";
            }
           
        }

        public override Hashtable setParameterHTable(ref string rptName)
        {
            reportTitle = "Projections";

            reportSource = PrepareTablesForDownload();
            StringWriter sw = new StringWriter();
            rptSource.WriteXml(sw, XmlWriteMode.WriteSchema);
            sXMLData = sw.ToString();

            reportCriteria = AddRefreshDatesToCriteria();

            //reportResultCount = "0";
            htParameter.Add("monthsRemaining", MonthsRemainingInProject);
            base.setParameterHTable(ref rptName);

            return htParameter;
        }

        public string MonthsRemainingInProject
        {
            get
            {
                return rptSource.Tables["MonthsRemainingInBudget"].Rows[0]["MonthsRemaining"].ToString();
            }
        }

        private string DateDifferenceInMonths(DateTime startDate, DateTime endDate)
        {
            return Convert.ToString(Math.Round((new TimeSpan(endDate.Ticks - startDate.Ticks).TotalDays * 12 / 365), 2));
        }

        private DataSet PrepareTablesForDownload()
        {
            DataTableCollection projectionsTables = ProjectionsDetails.GetDataContainer().Tables;
            DataSet trimmedProjections = new DataSet();

            foreach (DataTable dataTable in projectionsTables)
                trimmedProjections.Tables.Add(dataTable.Copy());

            DataTable category = trimmedProjections.Tables[AgreementsConstants.CategoryTableName];
            DataTable accountTable = trimmedProjections.Tables[AgreementsConstants.AccountsTableName];

            accountTable.Columns.Add(AccountTypeValueColName, typeof(System.Data.SqlTypes.SqlInt32));

            DataRowCollection accountRows = accountTable.Rows;
            foreach (DataRow account in accountRows)
            {
                account[AccountTypeValueColName] = Convert.ToInt32(account[AgreementConstants.AccountTypeColName]);

                DataRow[] expandedRows = category.Select(String.Format("{0} = {1} AND {2} = '{3}'",
                    AgreementConstants.CategoryIDColName, account[AgreementConstants.CategoryIDColName],
                    AgreementConstants.AccountIDColName, account[AgreementConstants.AccountIDColName]));

                foreach (DataRow expandedRow in expandedRows)
                    category.Rows.Remove(expandedRow);
            }
            trimmedProjections.AcceptChanges();
            return trimmedProjections;
        }

        private Projections ProjectionsDetails
        {
            get
            {
                Projections projections = Policy.ResultsCache.GetObject(cachePolicy, Projections.CacheKey) as Projections;
                if (projections == null)
                {
                    projections = new Projections();
                    projections.Load(Utility.DataAccess.GetConnectionString(),
                        userContext.DomainUserId, FundNumber, ClosingDate);
                    Policy.ResultsCache.SetObject(cachePolicy, Projections.CacheKey, projections);
                }
                return projections;
            }
        }

        private string FundNumber
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.ProjectionsDetailsPageKey) as Hashtable;
                return (h == null || h[FundNumberKey] == null) ? string.Empty : (string)h[FundNumberKey];
            }

            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.ProjectionsDetailsPageKey) as Hashtable;
                if (h == null) h = new Hashtable();
                h[FundNumberKey] = value;
                pageCachePolicy.Cache(Keys.ProjectionsDetailsPageKey, h);
            }
        }

        private string ClosingDate
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.ProjectionsDetailsPageKey) as Hashtable;
                return (h == null || h[ClosingDateKey] == null) ? DateTime.Now.ToShortDateString() :
                    (string)h[ClosingDateKey];
            }

            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.ProjectionsDetailsPageKey) as Hashtable;
                if (h == null) h = new Hashtable();
                h[ClosingDateKey] = value;
                pageCachePolicy.Cache(Keys.ProjectionsDetailsPageKey, h);
            }
        }

    }
}
